<?php


namespace app\controller\api;


use app\BaseController;
use app\models\user\DetailedMoneyModel;
use app\models\user\UserModel;
use think\facade\Db;

use app\services\config\ConfigService;
use app\services\user\UserService;


class PromoteController extends BaseController
{
    /**
     * 获取团队列表
     * @return \think\response\Json
     */
    public function getTeamList()
    {
        try {
            $userId = $this->request->userId;

            $userId = 486;

            $userInfo = UserService::geyUserInfo($userId);

            //$userInfo['label'] = 3;

            if (in_array($userInfo['label'], [1, 2, 3])) {
                $key_ary = [1 => 'good_credit_reporting', 2 => 'black_households', 3 => 'entrepreneurship'];

                $config_content = ConfigService::getConfigValue($key_ary[$userInfo['label']]);

                if($userInfo['label'] == 1){

                    //信用用户
                    $arr = UserModel::where('inviter', $userId)
                        ->where('status', 0)
                        ->where('is_reward', '0')
                        ->where('first_label', '1')
                        ->where('effective_purchase', '>', 0)
                        ->field('id,nick,mobile,create_time,referrer,relation')
                        ->select()
                        ->toArray();
                    $total = count($arr);
                    $team_num = $total;

                    $count = Db::name('user_promotion_rewards')->where('user_id',$userId)->where('label',1)->count();
                    if($count > 0){
                        $config_content = [];
                    }else{
                        foreach($config_content as $key => &$value){
                            $value['type'] = 0;
                            if($value['num'] <= $total) {
                                $value['type'] = 1;
                            }
                        }
                    }
                }elseif($userInfo['label'] == 2){

                    //黑户
                    $arr = UserModel::where('inviter', $userId)
                        ->where('status', 0)
                        ->where('is_reward', '0')
                        ->where('effective_purchase', '>', 0)
                        ->field('id,nick,mobile,create_time,referrer,relation')
                        ->select()
                        ->toArray();
                    $total = count($arr);
                    $team_num = $total;

                    foreach($config_content as $key => &$value){
                        $value['type'] = 0;
                        if($value['num'] <= $total){
                            $value['type'] = 1;
                        }
                    }

                    $config_content = [$config_content[$userInfo['accumulated_rewards']]];
                }elseif($userInfo['label'] == 3){
                    $arr = UserModel::where('inviter', $userId)
                        ->where('status', 0)
                        ->where('is_reward', '0')
                        ->where('effective_purchase', '>', 0)
                        //->field('id,nick,inviter,relation')
                        ->field('id,nick,mobile,sex,label,create_time,referrer,relation')
                        ->select()
                        ->each(function($item){
                            $user_ids =  Db::name('user')->where('status', 0)
                                ->where('is_reward', '0')
                                ->where('effective_purchase', '>', 0)
                                ->where('inviter',$item['id'])
                                ->column('id');
                            $item['tow_num'] = count($user_ids);
                            $item['tow_ids'] = $user_ids;

                            //获取三级用户人数
                            $item['three_num'] = 0;
                            $item['three_ids'] = [];

                            if($item['tow_num'] > 0){
                                $user_ids =  Db::name('user')->where('status', 0)
                                    ->where('is_reward', '0')
                                    ->where('effective_purchase', '>', 0)
                                    ->where('inviter','in',$item['tow_ids'])
                                    ->column('id');
                                $item['three_num'] = count($user_ids);
                                $item['three_ids'] = $user_ids;
                            }

                            $item['total'] = 1 + $item['tow_num'] + $item['three_num'];

                            $item['level_name'] = '一级';
                            return $item;
                        })->toArray();

                    $total = count($arr);
                    $team_num = array_sum(array_column($arr,'total'));

                    $tow_total = array_sum(array_column($arr,'tow_num'));
                    $three_total = array_sum(array_column($arr,'three_num'));

                    //三级奖励分别判断
                    $config = $config_content[$userInfo['accumulated_rewards']];
                    switch($userInfo['accumulated_rewards']){
                        case 0:
                            $config['type'] = $config['num'] <= $total ? 1 : 0;
                            break;
                        case 1:
                            $config['type'] = $config['num'] <= $tow_total ? 1 : 0;
                            break;
                        case 2:
                            $config['type'] = $config['num'] <= $three_total ? 1 : 0;
                            break;
                        default:
                            $config['type'] = 0;
                    }
                    $accumulated_rewards = [ "title" => "累计奖励", "num" => "0",'type' => $config['type'] == 1 ? 2 : 3];
                    $config_content = [
                        $config
                    ];
                    if($userInfo['accumulated_rewards'] != 2){
                        array_push($config_content,$accumulated_rewards);
                    }
                }

                foreach($arr as $key => &$item){
                    $item['create_time'] = date('Y-m-d',strtotime($item['create_time']));
                    $item['mobile'] = hideMobileMiddleFour($item['mobile']);
                    $item['level_name'] = '一级';
                }

                return $this->success(['total' => $total, 'team_num' => $team_num,'label' => $userInfo['label'], 'data' => $arr,'config_content' => $config_content]);
            } else {
                throw new \Exception('当前用户不符合推广要求');
            }
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }


    /**
     * 申请奖励
     * @return void
     */
    public function applyForRewards()
    {
        Db::startTrans();
        try {
            $userId = $this->request->userId;

            $userInfo = UserService::geyUserInfo($userId);

            if(!in_array($userInfo['label'], [1, 2, 3])){
                throw new \Exception('你不可以申请领奖');
            }

            $key_ary = [1 => 'good_credit_reporting', 2 => 'black_households', 3 => 'entrepreneurship'];
            $config_content = ConfigService::getConfigValue($key_ary[$userInfo['label']]);


            if($userInfo['label'] == 1){

                //信用用户
                $arr = UserModel::where('inviter', $userId)
                    ->where('status', 0)
                    ->where('is_reward', '0')
                    ->where('effective_purchase', '>', 0)
                    ->where('first_label', '1')
                    ->field('id,nick,mobile,create_time,referrer,relation')
                    ->select()
                    ->toArray();
                $total = count($arr);
            }elseif($userInfo['label'] == 2){

                //黑户
                $arr = UserModel::where('inviter', $userId)
                    ->where('status', 0)
                    ->where('is_reward', '0')
                    ->where('effective_purchase', '>', 0)
                    ->field('id,nick,mobile,create_time,referrer,relation')
                    ->select()
                    ->toArray();
                $total = count($arr);
                $tow_total = $total;
            }elseif($userInfo['label'] == 3){
                $arr = UserModel::where('inviter', $userId)
                    ->where('status', 0)
                    ->where('is_reward', '0')
                    ->where('effective_purchase', '>', 0)
                    //->field('id,nick,inviter,relation')
                    ->field('id,nick,mobile,sex,label,create_time,referrer,relation')
                    ->select()
                    ->each(function($item){
                        $user_ids =  Db::name('user')->where('status', 0)
                            ->where('is_reward', '0')
                            ->where('effective_purchase', '>', 0)
                            ->where('inviter',$item['id'])
                            ->column('id');
                        $item['tow_num'] = count($user_ids);
                        $item['tow_ids'] = $user_ids;

                        //获取三级用户人数
                        $item['three_num'] = 0;
                        $item['three_ids'] = [];

                        if($item['tow_num'] > 0){
                            $user_ids =  Db::name('user')->where('status', 0)
                                ->where('is_reward', '0')
                                ->where('effective_purchase', '>', 0)
                                ->where('inviter','in',$item['tow_ids'])
                                ->column('id');
                            $item['three_num'] = count($user_ids);
                            $item['three_ids'] = $user_ids;
                        }

                        $item['total'] = 1 + $item['tow_num'] + $item['three_num'];
                        return $item;
                    })->toArray();

                $total = count($arr);
                $tow_total = array_sum(array_column($arr,'tow_num'));
                $three_total = array_sum(array_column($arr,'three_num'));
            }
            $type = 0;
            switch($userInfo['accumulated_rewards']){
                case 0:
                    $type = $config_content[0]['num'] <= $total ? 1 : 0;
                    break;
                case 1:
                    $type = $config_content[1]['num'] <= $tow_total ? 1 : 0;
                    break;
                case 2:
                    $type = $config_content[2]['num'] <= $three_total ? 1 : 0;
                    break;
            }

            if($type == 0){
                throw new \Exception('你不符合领奖要求');
            }

            $promote_ids = array_column($arr, 'id');
            Db::name('user_promotion_rewards')->insert([
                'user_id' => $userId,
                'promote_ids' => implode(',', $promote_ids),
                'num' => $total,
                'type' => $type,
                'status' => 0,
                'create_time' => time(),
                'effective' => json_encode($config_content),
                'label' => $userInfo['label'],
                'accumulated_rewards' => $userInfo['accumulated_rewards']
            ]);

            //将相关用户清除团队
            if($userInfo['label'] == 2){
                Db::name('user')->where('id', 'in', $promote_ids)->update(['is_reward' => 1]);
                //黑户
                if($userInfo['accumulated_rewards'] == 1){
                    //领取第二次奖励
                    Db::name('user')->where('id', $userId)->update(['label' => '0','accumulated_rewards' => 0]);
                }else{
                    Db::name('user')->where('id', $userId)->update(['accumulated_rewards' => 1]);
                }
            }elseif($userInfo['label'] == 1){
                Db::name('user')->where('id', 'in', $promote_ids)->update(['is_reward' => 1]);
            }else{
                Db::name('user')->where('id', 'in', $promote_ids)->update(['is_reward' => 1]);
                Db::name('user')->where('id', $userId)->update(['label' => '0','accumulated_rewards' => 0]);
            }

            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 累计奖励
     * @return void
     */
    public function accumulated_rewards(){
        try {
            //accumulated_rewards
            $userId = $this->request->userId;

            //$userId = 469;

            $userInfo = UserService::geyUserInfo($userId);

            if($userInfo){
                $accumulated_rewards = $userInfo['accumulated_rewards'] + 1;

                if($accumulated_rewards > 2){
                    throw new \Exception('已经是最高级别的奖励了');
                }
                UserModel::where('id',$userId)->update(['accumulated_rewards' => $accumulated_rewards]);
            }else{
                throw new \Exception('当前用户未找到');
            }
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }
}